<template>
<div>
  <el-form class="pwdForm" ref="form" :model="form" :rules="rules" style="width: 600px" label-position="left" label-width="100px">
    <el-form-item label="旧密码" prop="oldPwd">
      <el-input
          type="password"
          v-model="form.oldPwd"
          show-password
          style="width: 300px;padding-left: 30px">
      </el-input>
    </el-form-item>

    <el-form-item label="新密码" prop="newPwd">
      <el-input
          type="password"
          v-model="form.newPwd"
          show-password
          style="width: 300px;padding-left: 30px">
      </el-input>
    </el-form-item>

    <el-form-item label="确认新密码" prop="reNewPwd">
      <el-input
          type="password"
          v-model="form.reNewPwd"
          show-password
          style="width: 300px;padding-left: 30px">
      </el-input>
    </el-form-item>

    <el-form-item style="margin-top: 50px;margin-left: 200px">
      <el-button type="primary" @click="submitForm('form')">保存</el-button>
    </el-form-item>
  </el-form>
</div>
</template>

<script>
export default {
  name: "ChangePwd",
  data() {
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
        // password 是表单上绑定的字段
      } else if (value !== this.form.newPwd) {
        callback(new Error('两次输入新密码不一致!'))
      } else {
        callback()
      }
    };
    return {
      form: {
        oldPwd: '',
        newPwd: '',
        reNewPwd: ''
      },
      rules: {
        oldPwd: [
          {required: true, message: '请填写旧密码', trigger: 'blur'}
        ],
        newPwd: [
          {required: true, message: '请填写新密码', trigger: 'blur'}
        ],
        reNewPwd: [
          {required: true, validator: validatePass2, trigger: 'blur'}
        ]
      },
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.put(`${this.HOST}/user/changepwd`,{
            form: this.form
          },{
            header: {
              'Content-Type': 'multipart/form-data'
            }
          }).then(res => {
            this.$message({
              message: res.data.message,
              type: 'success',
              offset: 90,
              duration: 1000
            })
          })
        } else {
          return false;
        }
      });
    },
  }
}
</script>

<style scoped>
.pwdForm {
  width: 400px;
  height: 600px;
  margin-top: 100px;
  margin-left: 50px;
}
</style>
